package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.task.WebSocketTask;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;



/**
 * 订单
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShopCarMapper shopCarMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //异常情况的处理（收货地址为空、购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shopCarMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        //向订单表插入1条数据
        orderMapper.insert(order);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }

        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车中的数据
        shopCarMapper.deleteByUserId(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult lookhistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //获取分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //获取当前线程id给用户id
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //根据id查询当前订单
        Page<Orders> page=orderMapper.page(ordersPageQueryDTO);
        //获取订单结果数据
        List<Orders> result = page.getResult();
        //定义封装OrdersVo
        List<OrderVO> list = new ArrayList<>();
        //判断用户是否存在该订单
        if(page!=null&&page.size()>0){
            //根据订单id遍历订单详情
            for (Orders orders : result) {
                List<OrderDetail> orderDetailList = orderDetailMapper.getBYOrdersId(orders.getId());
                OrderVO orderVO = new OrderVO();
                //把orders的值赋给orderVo
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                list.add(orderVO);
            }
            }
        return new PageResult(page.getTotal(),list);
    }

    /**
     * 订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO lookOrdersDetail(Long id) {
        //获取订单id,根据id查询订单表
       /* Orders orders = new Orders();
        Long ordersId = orders.getId();*/
        Orders orders = Orders.builder().id(id).build();
        orders=orderMapper.getOrders(orders);
        //根据id查询订单详情
        List<OrderDetail> byOrdersId = orderDetailMapper.getBYOrdersId(id);
        //封装返回结果
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(byOrdersId);
        return orderVO;
    }



    /**
     * 取消订单
     * @param id
     * @return
     */
    @Override
    public void cancelOrders(Long id) {
        //创建orders对象，设置id，取消时间，状态
        Orders orders = new Orders();
        orders.setId(id);
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);

    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetitionOrders(Long id) {
        //根据id获取订单详情
        Orders orders = Orders.builder().id(id).build();
         orders = orderMapper.getOrders(orders);
        //判断订单是否存在
        if(orders==null){
             throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单存在，再来一单需要返回购物车，添加订单信息
        List<OrderDetail> byOrdersId = orderDetailMapper.getBYOrdersId(id);
        for (OrderDetail orderDetail : byOrdersId) {
           ShoppingCart shoppingCart=ShoppingCart.builder().
                   name(orderDetail.getName()).
                   image(orderDetail.getImage()).
                   userId(BaseContext.getCurrentId()).
                   dishId(orderDetail.getDishId()).
                   number(orderDetail.getNumber()).
                   amount(orderDetail.getAmount()).
                   createTime(LocalDateTime.now()).
                   setmealId(orderDetail.getSetmealId()).
                   dishFlavor(orderDetail.getDishFlavor()).build();
            shopCarMapper.insert(shoppingCart);
            //shopCarMapper.list(shoppingCart);
        }

    }

    /**
     * 搜索订单
     * @return
     */
    @Override
    public PageResult searchOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //获取分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //根据id查询当前订单
        Page<Orders> page=orderMapper.page(ordersPageQueryDTO);
        //获取订单结果数据
        List<Orders> result = page.getResult();
        //定义封装OrdersVo
        List<OrderVO> list = new ArrayList<>();
        //判断用户是否存在该订单
        if(page!=null&&page.size()>0){
            //根据订单id遍历订单详情
            for (Orders orders : result) {
                List<OrderDetail> orderDetailList = orderDetailMapper.getBYOrdersId(orders.getId());
                OrderVO orderVO = new OrderVO();
                //把orders的值赋给orderVo
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(),list);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statisticsNumber() {
       //待接单
        Integer waitOrders=orderMapper.getStatistics(Orders.TO_BE_CONFIRMED);
        //已接单
        Integer orders=orderMapper.getStatistics(Orders.CONFIRMED);
        //派送中
        Integer ordering=orderMapper.getStatistics(Orders.DELIVERY_IN_PROGRESS);
        //创建对象
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //将上面状态给到上面的对象
        //待接单数量
        orderStatisticsVO.setToBeConfirmed(waitOrders);
        //派送中数量
        orderStatisticsVO.setDeliveryInProgress(orders);
        //带派送数量
        orderStatisticsVO.setConfirmed(ordering);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirmOrders(OrdersConfirmDTO ordersConfirmDTO) {
        //查询订单的id和状态,更新订单状态
        Orders orders = Orders.builder().id(ordersConfirmDTO.getId()).
                status(Orders.CONFIRMED).build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
   @SneakyThrows
    @Override
    public void rejectionOrders(OrdersRejectionDTO ordersRejectionDTO) {
        //只有当订单状态为2时即待接单才能进行拒单操作，然后进行退款
        //根据id查询订单状态是否为2
        log.info("拒单：{}",ordersRejectionDTO);
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        if(orders==null||orders.getStatus()!=(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);//订单状态错误
        }
        //获取支付状态，进行退款
        /*Integer payStatus = orders.getPayStatus();
        //判断支付状态是否为已支付状态,进行退款
        if(payStatus==Orders.PAID){
            String refund = weChatPayUtil.refund(orders.getNumber(),//商家订单号
                    orders.getNumber(),//商家退单号
                    orders.getAmount(),//退款金额
                    orders.getAmount()//原定金额

            );
            log.info("退款:{}",refund);*/
            //拒单后需要修改订单状态
            Orders orders1 = Orders.builder().id(orders.getId()).status(Orders.CANCELLED).//已取消订单
                    cancelTime(LocalDateTime.now()).
                    cancelReason(ordersRejectionDTO.getRejectionReason()).//取消订单原因
                            build();
            orderMapper.update(orders1);
        }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrdersId(OrdersCancelDTO ordersCancelDTO) {
    //当订单正在派送中时不能取消订单，根据id获取订单状态
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        if(orders.getStatus()==(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders build = Orders.builder().id(orders.getId()).status(Orders.CANCELLED).
                cancelReason(ordersCancelDTO.getCancelReason()).
                cancelTime(LocalDateTime.now()).build();
        orderMapper.update(build);


    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void deliveryOrders(Long id) {
        //获取订单状态，当订单状态为3即已付款才能派送
        Orders orders = orderMapper.getById(id);
        if(orders==null||orders.getStatus()!=Orders.CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //派送后修改订单状态
        Orders  orders1= Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build();
        orderMapper.update(orders1);
    }

    @Override
    public void completeOrders(Long id) {
        //获取订单状态，当订单状态为即派送中才能派送
        Orders orders = orderMapper.getById(id);
        if(orders==null||orders.getStatus()!=Orders.DELIVERY_IN_PROGRESS){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //派送后修改订单状态
        Orders  orders1= Orders.builder().id(id).status(Orders.COMPLETED).build();
        orderMapper.update(orders1);
    }
    /**
     *催单
     */
    @Override
    public void reminder(Long id) {
            //根据id查询订单是否存在
            Orders orders = orderMapper.getById(id);
            if(orders==null){
                throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
            }
            //基于webosocket实现催单
            HashMap map = new HashMap();
            //消息类型 ，2催单业务
            map.put("type",2);
            map.put("orderId",orders.getId());
            //订单号
            map.put("content","订单号"+orders.getNumber());
            webSocketServer.sendToAllClient(JSON.toJSONString(map));

        }
    }











